<?php

use Service\AlipayOpenPlatform\AopFactory;
use Service\Exception\ApiErrCode;
use Service\Utils\SimpleQrCode;

class ControllerAccountLogin extends Controller {

    const SCAN_QRCODE_LOGIN_EXPIRATION_DATE = 60; // App端扫码登录的code有效期

	private $error = array();

    /**
     * @throws Exception
     */
    public function index() {
		if ($this->customer->isLogged()) {
			$this->response->redirect($this->url->link('account/account'));
		}

		$this->load->language('account/login');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('account/customer');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			// Unset guest
			unset($this->session->data['guest']);

			// Default Shipping Address
			$this->load->model('account/address');

			if ($this->config->get('config_tax_customer') == 'payment') {
				$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
			}

			if ($this->config->get('config_tax_customer') == 'shipping') {
				$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
			}

			// Wishlist
			if (isset($this->session->data['wishlist']) && is_array($this->session->data['wishlist'])) {
				$this->load->model('account/wishlist');

				foreach ($this->session->data['wishlist'] as $key => $product_id) {
					$this->model_account_wishlist->addWishlist($product_id);

					unset($this->session->data['wishlist'][$key]);
				}
			}

			// Log the IP info
			$this->model_account_customer->addLogin($this->customer->getId(), $this->request->server['REMOTE_ADDR']);

			$this->bindCustomerIfOauthRegister();

			// Added strpos check to pass McAfee PCI compliance test (http://forum.opencart.com/viewtopic.php?f=10&t=12043&p=151494#p151295)
			if (isset($this->request->post['redirect']) && $this->request->post['redirect'] != $this->url->link('account/logout') && (strpos($this->request->post['redirect'], $this->config->get('config_url')) !== false)) {
				$this->response->redirect(str_replace('&amp;', '&', $this->request->post['redirect']));
			} else {
				$this->response->redirect($this->url->link('common/home'));
			}
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/home')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_account'),
			'href' => $this->url->link('account/account')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_login'),
			'href' => $this->url->link('account/login')
		);

		if (isset($this->session->data['error'])) {
			$data['error_warning'] = $this->session->data['error'];

			unset($this->session->data['error']);
		} elseif (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

        $oauth_type = $this->request->get['oauth_type'];
        $oauth_user_id = $this->request->get['oauth_user_id'];
        $data['is_binding'] = isset($oauth_type) && isset($oauth_user_id);
        $link_arguments = $data['is_binding'] ? compact('oauth_type', 'oauth_user_id') :'';
		$data['action'] = $this->url->link('account/login', $link_arguments);

		$data['register'] = $this->url->link('account/register');
		$data['forgotten'] = $this->url->link('account/forgotten');

		// Added strpos check to pass McAfee PCI compliance test (http://forum.opencart.com/viewtopic.php?f=10&t=12043&p=151494#p151295)
		if (isset($this->request->post['redirect']) && (strpos($this->request->post['redirect'], $this->config->get('config_url')) !== false)) {
			$data['redirect'] = $this->request->post['redirect'];
		} elseif (isset($this->session->data['redirect'])) {
			$data['redirect'] = $this->session->data['redirect'];

			unset($this->session->data['redirect']);
		} else {
			$data['redirect'] = '';
		}

		if (isset($this->session->data['success'])) {
			$data['success'] = $this->session->data['success'];

			unset($this->session->data['success']);
		} else {
			$data['success'] = '';
		}

		if (isset($this->request->post['email'])) {
			$data['email'] = $this->request->post['email'];
		} else {
			$data['email'] = '';
		}

        if (isset($this->request->post['login_type'])) {
            $data['login_type'] = $this->request->post['login_type'];
        } else {
            $data['login_type'] = 'mobile';
        }

        if (isset($this->request->post['telephone'])) {
            $data['telephone'] = $this->request->post['telephone'];
        } else {
            $data['telephone'] = '';
        }



		if (isset($this->request->post['password'])) {
			$data['password'] = $this->request->post['password'];
		} else {
			$data['password'] = '';
		}

		$data['column_left'] = $this->load->controller('common/column_left');
		$data['column_right'] = $this->load->controller('common/column_right');
		$data['content_top'] = $this->load->controller('common/content_top');
		$data['content_bottom'] = $this->load->controller('common/content_bottom');
		$data['footer'] = $this->load->controller('common/footer');
		$data['header'] = $this->load->controller('common/header');

        $data['login_background_image'] = $this->loginBackGroundImg();
        $data['oauth_login_actions'] = $this->oauthLoginActions();

		$this->response->setOutput($this->load->view('account/login', $data));
	}

	protected function validate() {
		// Check if customer has been approved.
        $email = $this->request->post['email'] ?? null;
        $telephone = $this->request->post['telephone'] ?? null;
        $dial_code = $this->request->post['dial_code'] ?? null;

        if ($email) {
            $customer_info = $this->model_account_customer->getCustomerByEmail($email);
        } else if ($telephone) {
            $customer_info = $this->model_account_customer->getCustomerByTelephone($telephone, $dial_code);
        } else {
            $customer_info = null;
        }

		if ($customer_info) {
            // Check how many login attempts have been made.
            $login_info = $this->model_account_customer->getLoginAttempts($customer_info['customer_id']);

            if ($login_info && ($login_info['total'] >= $this->config->get('config_login_attempts')) && strtotime('-1 hour') < strtotime($login_info['date_modified'])) {
                $this->error['warning'] = $this->language->get('error_attempts');
            }
        }

		if ($customer_info && !$customer_info['status']) {
			$this->error['warning'] = $this->language->get('error_approved');
		}

		if (!$this->error) {
			if (!$customer_info || !$this->customer->login($customer_info['customer_id'], $this->request->post['password'])) {
				$this->error['warning'] = $this->language->get('error_login');

			    if ($customer_info) {
				    $this->model_account_customer->addLoginAttempt($customer_info['customer_id']);
                }
			} else {
			    if ($customer_info) {
				    $this->model_account_customer->deleteLoginAttempts($customer_info['customer_id']);
                }
			}
		}

		return !$this->error;
	}

	public function token() {
		$this->load->language('account/login');

		if (isset($this->request->get['email'])) {
			$email = $this->request->get['email'];
		} else {
			$email = '';
		}

		if (isset($this->request->get['login_token'])) {
			$token = $this->request->get['login_token'];
		} else {
			$token = '';
		}

		// Login override for admin users
		$this->customer->logout();
		$this->cart->clear();

		unset($this->session->data['order_id']);
		unset($this->session->data['payment_address']);
		unset($this->session->data['payment_method']);
		unset($this->session->data['payment_methods']);
		unset($this->session->data['shipping_address']);
		unset($this->session->data['shipping_method']);
		unset($this->session->data['shipping_methods']);
		unset($this->session->data['comment']);
		unset($this->session->data['coupon']);
		unset($this->session->data['reward']);
		unset($this->session->data['voucher']);
		unset($this->session->data['vouchers']);
        unset($this->session->data['credit']);

		$this->load->model('account/customer');

		$customer_info = $this->model_account_customer->getCustomerByEmail($email);

		if ($customer_info && $customer_info['token'] && $customer_info['token'] == $token && $this->customer->login($customer_info['customer_id'], '', true)) {
			// Default Addresses
			$this->load->model('account/address');

			if ($this->config->get('config_tax_customer') == 'payment') {
				$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
			}

			if ($this->config->get('config_tax_customer') == 'shipping') {
				$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
			}

			$this->model_account_customer->editToken($customer_info['customer_id'], '');

			$this->response->redirect($this->url->link('account/account'));
		} else {
			$this->session->data['error'] = $this->language->get('error_login');

			$this->model_account_customer->editToken($customer_info['customer_id'], '');

			$this->response->redirect($this->url->link('account/login'));
		}
	}

	/**
     * 使用插件控制器处理第三方登录 回调
     *
     * @example
     * @throws Exception
     */
    public function oauthCallback()
    {
        $type = $this->requestGet('type');

        /**
         * @uses ControllerExtensionOauthWechatPc::callback()
         * @uses ControllerExtensionOauthAlipayPc::callback()
         */
        $redirect_url = $this->load->controller('extension/oauth/' . $type . '/callback');

        $this->response->redirect($redirect_url);
    }

    /**
     *  生成手机扫码登录的二维码
     */
    public function generateQrCode()
    {
        $token = md5(date('YmdHisu').rand(0, 9999));
        $image_string = SimpleQrCode::toImage($token);

        // 设置有效期
        setCookie('qrcode-'.$token, true, time() + self::SCAN_QRCODE_LOGIN_EXPIRATION_DATE);

        $image = ['qr_code' => 'data:image/jpg;base64,'.base64_encode($image_string), 'qr_code_token' => $token];

        $this->responseOK($image);
    }

    /**
     * 轮询扫码是否成功
     */
    public function polling()
    {
        $qr_code_token = $this->request->get['qr_code_token'];

        $this->load->language('account/login');

        // token是否过期了！
        if (!isset($_COOKIE['qrcode-'.$qr_code_token])) {
            $data = ['code' => ApiErrCode::SCAN_QRCODE_LOGIN_TIMEOUT, 'msg' => $this->language->get('code_timeout')];
        } else {
            $data = ['code' => ApiErrCode::SCAN_QRCODE_LOGIN_NO, 'msg' => '二维码未扫描，请扫描二维码'];
        }

        $this->load->model('account/customer');
        $customer = $this->model_account_customer->getCustomerByCode($this->request->get['qr_code_token']);

        if ($customer) {

            if ($this->validateDateUpdated($customer['date_updated'])) {
                $this->customer->loginByCustomerId($customer['customer_id']);
                $data = [
                    'code'     => ApiErrCode::SCAN_QRCODE_LOGIN_SUCCESS,
                    'msg'      => $this->language->get('scan_success'),
                    'redirect' => $this->getLoginRedirectUrl(),
                ];
            } else {
                $data = ['code' => ApiErrCode::SCAN_QRCODE_LOGIN_TIMEOUT, 'msg' => $this->language->get('code_timeout')];
            }
        }

        $this->responsejson($data);
    }

    /**
     *
     */
    protected function bindCustomerIfOauthRegister()
    {
        $oauth_type = $this->requestGet('oauth_type');
        $oauth_user_id = $this->requestGet('oauth_user_id');
        if ($this->customer->getId() && $oauth_type && $oauth_user_id) {
            $this->load->controller('extension/oauth/' . $oauth_type . '/bindCustomer');
        }
    }

    /**
     * @return array
     *
     * @throws Exception
     */
    private function oauthLoginActions()
    {
        /** @var ModelSettingExtension $modelExtension */
        $modelExtension = $this->loadModel('setting/extension');

        $extensions = $modelExtension->getExtensions('oauth');

        $pc_extensions = array_filter($extensions, function ($extension) {
            $is_pc = strpos($extension['code'], 'pc') !== false;
            $is_enabled = $this->config->get('oauth_' . $extension['code'] . '_status');
            return $is_pc && $is_enabled;
        });

        $actions = array_map(function ($extension) {
            return $this->load->controller('extension/oauth/' . $extension['code']. '/loginAction');
        }, $pc_extensions);

        // sort by
        usort($actions, function ($actionA, $actionB) {
            return $actionA['sort_order'] - $actionB['sort_order'];
        });

        return $actions;
    }

    /**
     *
     * @return string
     */
    public function oauthSuccess()
    {
        $data['account_page'] = $this->url->link('common/home');

        $this->response->setOutput($this->load->view('account/oauth_success', $data));
    }

    /**
     * @param $date_updated
     * @return bool
     */
    private function validateDateUpdated($date_updated)
    {
        date_default_timezone_set(OC_TIME_ZONE);

        if (time() - strtotime($date_updated) <= self::SCAN_QRCODE_LOGIN_EXPIRATION_DATE) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @return mixed
     */
    private function getLoginRedirectUrl()
    {
        if (empty($this->session->data['redirect'])) {
            $url = $this->url->link('common/home');
        } else {
            $url = $this->session->data['redirect'];
        }

        return $this->response->normalizeUrlLink($url);
    }
}
